package com.heima.search.service.impl;

import com.alibaba.fastjson.JSON;
import com.heima.common.constants.datasync.DataSyncIndexConstants;
import com.heima.common.exception.CustException;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.search.dtos.UserSearchDto;
import com.heima.model.search.vos.SearchArticleVo;
import com.heima.model.user.pojos.ApUser;
import com.heima.search.service.ApUserSearchService;
import com.heima.search.service.ArticleSearchService;
import com.heima.utils.threadlocal.AppUserThreadLocalUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.elasticsearch.action.delete.DeleteRequest;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.text.Text;
import org.elasticsearch.common.xcontent.XContentType;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.sort.SortOrder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

@Service
@Slf4j
public class ArticleSearchServiceImpl implements ArticleSearchService {

    @Autowired
    RestHighLevelClient restHighLevelClient;
    @Autowired
    ApUserSearchService apUserSearchService;
    @Value("${file.oss.web-site}")
    String webSite;

    /**
     * 搜索分页查询
     * @param dto
     * @return
     */
    @Override
    public ResponseResult search(UserSearchDto dto) {
        //参数校验
        if(dto==null||StringUtils.isBlank(dto.getSearchWords())){
            CustException.cust(AppHttpCodeEnum.PARAM_REQUIRE);
        }
        if(dto.getPageSize()<0){
            dto.setPageSize(10);
        }
        if(dto.getMinBehotTime()==null){
            dto.setMinBehotTime(new Date());
        }
        //如果用户登录记录查询记录
        ApUser user = AppUserThreadLocalUtils.getUser();
        if(user!=null){
            dto.setEntryId(user.getId());
        }
        //异步保存用户的搜索记录
        apUserSearchService.insert(dto);
        //创建搜索请求
        SearchRequest request = new SearchRequest(DataSyncIndexConstants.ARTICLE_INDEX_NAME);
        SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
        //构建查询条件
        BoolQueryBuilder boolQueryBuilder = new BoolQueryBuilder();
        boolQueryBuilder.must(QueryBuilders.matchQuery("title",dto.getSearchWords()))
                .filter(QueryBuilders.rangeQuery("publishTime").lt(dto.getMinBehotTime()));
        //分页条件
        searchSourceBuilder.from(0).size(dto.getPageSize());
        //按照发布时间倒序排列
        searchSourceBuilder.sort("publishTime",SortOrder.DESC);
        //设置搜索条件高亮显示
        HighlightBuilder highlightBuilder = new HighlightBuilder();
        highlightBuilder.field("title").preTags("<font style='color:red'>").postTags("</font>");
        searchSourceBuilder.highlighter(highlightBuilder).query(boolQueryBuilder);
        request.source(searchSourceBuilder);
        try {
            SearchResponse searchResponse = restHighLevelClient.search(request, RequestOptions.DEFAULT);
            //解析结果
            SearchHits searchHits = searchResponse.getHits();
            ArrayList<SearchArticleVo> articleVoList = new ArrayList<>();
            log.info("总记录数：{}"+searchHits.getTotalHits().value);
            SearchHit[] hits = searchHits.getHits();
            for (SearchHit hit : hits) {
                String hitStr = hit.getSourceAsString();
                //将字符串转换成对象
                SearchArticleVo searchArticleVo = JSON.parseObject(hitStr, SearchArticleVo.class);
                //获取高亮结果替换原有数据
                Text[] titles = hit.getHighlightFields().get("title").getFragments();
                String title = StringUtils.join(titles);
                //修改images，拼接前缀
                String images = addPrefix(searchArticleVo);
                searchArticleVo.setImages(images);
                searchArticleVo.setTitle(title);
                articleVoList.add(searchArticleVo);
            }
            ResponseResult responseResult = ResponseResult.okResult(articleVoList);
            responseResult.setHost(webSite);
            return responseResult;
        } catch (IOException e) {
            e.printStackTrace();
        }
        return ResponseResult.errorResult(AppHttpCodeEnum.SERVER_ERROR);
    }

    /**
     * 向es索引库中添加文章
     * @param articleId
     * @param article
     */
    @Override
    public void saveArticle(String articleId, SearchArticleVo article) {
        //创建添加请求
        IndexRequest indexRequest = new IndexRequest(DataSyncIndexConstants.ARTICLE_INDEX_NAME);
        indexRequest.id(articleId).source(JSON.toJSONString(article),XContentType.JSON);
        try {
            restHighLevelClient.index(indexRequest,RequestOptions.DEFAULT);
        } catch (IOException e) {
            e.printStackTrace();
            log.error("索引库添加文章数据失败: {}",article);
        }
    }

    /**
     * 从es索引库中删除文章
     * @param articleId
     */
    @Override
    public void deleteArticle(String articleId) {
        DeleteRequest deleteRequest = new DeleteRequest(DataSyncIndexConstants.ARTICLE_INDEX_NAME);
        deleteRequest.id(articleId);
        try {
            restHighLevelClient.delete(deleteRequest,RequestOptions.DEFAULT);
        } catch (IOException e) {
            e.printStackTrace();
            log.error("索引库删除文章数据失败: {}",articleId);
        }
    }

    /**
     * 为封面拼接前缀方法
     * @param searchArticleVo
     * @return
     */
    private String addPrefix(SearchArticleVo searchArticleVo) {
        List<String> imageList = Arrays.asList(searchArticleVo.getImages().split(","));
        return imageList.stream().map(image -> webSite + image).collect(Collectors.joining(","));
    }
}
